package com.mes.controller;

import com.mes.entity.*;
import com.mes.service.InformWorkService;
import com.yy.base.page.Message;
import com.yy.base.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

/**
 * 完工报检
 */
@Controller
@RequestMapping(value = "/data")
public class InformWorkController {
	private SimpleDateFormat dateSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
	private InformWorkService service;
	/**
	 * 报工
	 */
	@ResponseBody
	@Transactional
	@RequestMapping(value = "/submitInformWork.html", method = RequestMethod.POST)
	public Message informWork(HttpServletRequest request, HttpServletResponse response) {
		Message message = new Message();
		try {
			Long qty = Long.parseLong(request.getParameter("qty"));
			if (qty <= 0) {
				message.setErrorMessage("报工数量必须大于0！");
				return message;
			}
			if (request.getParameter("startTime") == null || "".equals(request.getParameter("startTime"))) {
				message.setErrorMessage("未接收到开工时间！");
				return message;
			}
			
			Timestamp startTime = new Timestamp(dateSDF.parse(request.getParameter("startTime")).getTime());
			
			EmesoManuOrderJobOrder jobOrder = service.getJobOrderInfo(request.getParameter("orderCode"));
	
			if (jobOrder == null) {
				message.setErrorMessage("作业订单不存在！");
				return message;
			}
			if (!"START".equals(jobOrder.getStatus())) {
				message.setErrorMessage("作业订单不是开工状态！");
				return message;
			}
			long exeTime = 0;
			if (request.getParameter("exeTime") != null) {
				exeTime = Long.parseLong(request.getParameter("exeTime"));
			} else {
				exeTime = jobOrder.getProcessTime();
			}
			long orderQtyDone = new BigDecimal(jobOrder.getQtyDone() == null ? 0 : jobOrder.getQtyDone()).add(new BigDecimal(qty)).longValue();
			long orderQtyStart = new BigDecimal(jobOrder.getQtyStart() == null ? 0 : jobOrder.getQtyStart()).add(new BigDecimal(qty)).longValue();

			long canQty = service.getCanStartWork(jobOrder.getMaunOrderId(), jobOrder.getRouteNo());
			if (canQty > -1 && orderQtyStart > canQty) {
				message.setErrorMessage("完工数量不能大于可开工数量！");
				return message;
			}
			
			jobOrder.setQtyDone(orderQtyDone);
			jobOrder.setQtyStart(orderQtyStart);
			
			Timestamp exeDateTo = new Timestamp(System.currentTimeMillis());
			
			if (jobOrder.getQtyDone() >= jobOrder.getQty()) {
				jobOrder.setStatus("FINISHED");//完工
				jobOrder.setExeDateTo(exeDateTo);
			}
			
			service.updateJobOrderInfo(jobOrder);
			
			User user = (User)request.getSession().getAttribute("user");
			
			//更新作业信息
			updateJobInfo(jobOrder.getOrderJobId(), qty, exeDateTo);
	
			EmesoJobOrderExe jobExe = new EmesoJobOrderExe();
			jobExe.setId(StringUtil.getUUID());
			jobExe.setJobOrderId(jobOrder.getId());
			jobExe.setUserId(user.getId());
			jobExe.setOperatorUser(user);
			jobExe.setDescription(request.getParameter("description"));
			
			jobExe.setExeDateFrom(startTime);
			jobExe.setExeDateTo(exeDateTo);
			
			// 完工数量=作业订单处理数量-开工数量
			jobExe.setQty(qty);
			jobExe.setQtyDone(qty);
	
			jobExe.setExeTime(exeTime);
			
			if ("Y".equals(jobOrder.getIsQuality())) {
				jobExe.setStatus("CREATE");//待检
			} else {
				jobExe.setStatus("FINISHED");//完工
			}
			jobExe.setIsQuality(jobOrder.getIsQuality());//是否需要质检
			
			if (request.getParameter("codeStart") != null && !"".equals(request.getParameter("codeStart"))) {
				jobExe.setCodeStart(Integer.parseInt(request.getParameter("codeStart")));
			}
			if (request.getParameter("codeEnd") != null && !"".equals(request.getParameter("codeEnd"))) {
				jobExe.setCodeEnd(Integer.parseInt(request.getParameter("codeEnd")));
			}
			
			service.saveJobExeInfo(jobExe);
			
			service.syncUpdateOrderStatus();
			
			message.setOkMessage("提交成功！");
		} catch (Exception e) {
			e.printStackTrace();
			message.setErrorMessage("提交报工异常：" + e.getMessage());
		}
		return message;
	}

	//更新生产订单工序信息数据
	private void updateJobInfo(String orderJobId, long qtyDone, Timestamp exeDateTo) {
		EmesoJobOrder job = service.getOrderJobInfo(orderJobId);
		long orderQtyDone = new BigDecimal(job.getQtyDone() == null ? 0 : job.getQtyDone()).add(new BigDecimal(qtyDone)).longValue();
		long orderQtyStart = new BigDecimal(job.getQtyStart() == null ? 0 : job.getQtyStart()).add(new BigDecimal(qtyDone)).longValue();
		job.setQtyDone(orderQtyDone);
		job.setQtyStart(orderQtyStart);
		
		if (job.getQtyDone() >= job.getQty()) {
			job.setStatus("FINISHED");
			job.setExeDateTo(exeDateTo);
		}

		service.updateOrderJobInfo(job);
	}

	@ResponseBody
	@Transactional
	@RequestMapping(value = "/startWork.html", method = RequestMethod.POST)
	public Message startWork(HttpServletRequest request, HttpServletResponse response) {
		Message message = new Message();
		try {
			String code = request.getParameter("orderCode");
			EmesoManuOrderJobOrder jobOrder = service.getJobOrderInfo(code);

			long canQty = service.getCanStartWork(jobOrder.getMaunOrderId(), jobOrder.getRouteNo());
			if (canQty == 0) {
				if ("Y".equals(jobOrder.getIsQuality())) {
					message.setErrorMessage("上一道工序未报工或未检验合格，当前工序无法开工");
				} else {
					message.setErrorMessage("上一道工序未报工，当前工序无法开工");
				}
				return message;
			}
			//TODO 未做BOM清单完工状态判断

			Timestamp date = null;
			if ("CREATE".equals(jobOrder.getStatus())) {
				date = new Timestamp(System.currentTimeMillis());
				jobOrder.setStatus("START");// 开工
				jobOrder.setExeDateFrom(date);
				service.updateJobOrderInfo(jobOrder);
			} else {
				date = jobOrder.getExeDateFrom();
			}
			message.setData("exeDateFrom", dateSDF.format(date));

			message.setData("result", true);
		} catch (Exception e) {
			e.printStackTrace();
			message.setErrorMessage("获取订单信息异常：" + e.getMessage());
		}
		return message;
	}

	@ResponseBody
	@Transactional
	@RequestMapping(value = "/getJobOrderInfo.html", method = RequestMethod.POST)
	public Message getJobOrderInfo(HttpServletRequest request, HttpServletResponse response) {
		Message message = new Message();
		try {
			String code = request.getParameter("orderCode");
			EmesoManuOrderJobOrder info = service.getJobOrderInfo(code);
			if (info == null) {
				message.setErrorMessage("作业订单号不存在");
				return message;
			}
			if ("OK".equals(info.getStatus()) || "FINISHED".equals(info.getStatus())) {
				message.setErrorMessage("该作业订单已报工完成");
				return message;
			}
			message.setData("qty", info.getQty());
			message.setData("qtyStart", info.getQtyStart());
			message.setData("status", info.getStatus());
			message.setData("routeNo", info.getRouteNo());
			message.setData("routeName", info.getRouteName());
			
			if (info.getExeDateFrom() != null) {
				message.setData("exeDateFrom", dateSDF.format(info.getExeDateFrom()));
			}
			
			EmesoManuOrder manuOrder = service.getManuOrderInfo(info.getMaunOrderId());
			message.setData("code", manuOrder.getCode());
			message.setData("productCode", manuOrder.getProductCode());
			message.setData("productName", manuOrder.getProductName());
			message.setData("productName2", manuOrder.getProductName2());
			
			message.setData("result", true);
		} catch (Exception e) {
			e.printStackTrace();
			message.setErrorMessage("获取订单信息异常：" + e.getMessage());
		}
		return message;
	}
}
